<template>
    <div class="app-container">
    	<div>
	      <p class="dialogTitle title">当前地震事件:
	        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
	        <span v-else>请在地震事件管理中设置当前地震事件</span>
	      </p>
	    </div>
        <!--<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" v-show="showSearch">
            <el-form-item label="地震事件名称" prop="area">
                <el-input v-model="form.area" placeholeder="请输入地震事件名称" ></el-input>
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>-->

        <!--<el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent"
                    @click="importTemplate('总建筑面积导入模板.xlsx')">导出模版</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" :disabled="!currentEvent&&multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>-->

        <el-table v-loading="loading" :data="dataList" stripe row-key="id" @selection-change="handleSelectionChange" border >
            <!--<el-table-column type="selection" align="center" :reserve-selection="true" width="55" />-->
            <el-table-column label="序号" align="center" width="55">
                <template #default="scope">
                    <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="地震事件编号" align="center" prop="eventCode" show-overflow-tooltip />
            <el-table-column label="地震事件名称" align="center" prop="eventName" show-overflow-tooltip />
            <el-table-column label="专家意见" align="center" prop="expertOpinion" />
            <el-table-column label="专家意见pdf文件" align="center" prop="expertOpinionPdf">
            	<template #default="scope">
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownload(scope.row.expertOpinionPdf)">
				          <span v-if="scope.row.expertOpinionPdfAtt">{{ scope.row.expertOpinionPdfAtt[0].attachName }} </span>
				        </el-link>
              </template>
            </el-table-column>
            <el-table-column label="地震烈度图" align="center" prop="seismicIntensityMap" >
            	<template #default="scope">
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownload(scope.row.seismicIntensityMap)">
				          
				          <span v-if="scope.row.seismicIntensityMapAtt">{{ scope.row.seismicIntensityMapAtt[0].attachName }} </span>
				          
				        </el-link>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="handleEdit(scope.row)">地震烈度图资料</el-button>                 
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="addRef" label-width="170px" :model="form" :rules="rules">
                <el-row style="margin: 20px 0;">
                    <el-col>
                      <el-form-item label="专家意见" prop="expertOpinion" required>
                          <el-input type="textarea" :rows="4" v-model="form.expertOpinion" placeholeder="请输入专家意见" ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="专家意见（pdf）" prop="expertOpinionPdf" required>
							          <file-upload ref="fileUpload" v-model="form.expertOpinionPdfAtt" :fileType="['pdf']" :limit="1"/>
							        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="地震烈度图（终版）jpg" prop="seismicIntensityMap" required>
								          <image-upload ref="imageUpload"  v-model="form.seismicIntensityMapAtt"  @uploadSuccess="imgUploadSuccess" :fileType="['jpg']" :limit="1"></image-upload>	
													
								        </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="过程材料（可上传多个，不超过10个）">
							          <file-upload ref="fileUpload1" :limit="10" v-model="form.processMaterialsAtt"/>
							        </el-form-item>
                    </el-col>
                    
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="save">保 存</el-button>
                    <el-button @click="open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess"
                :data="{ 'xsemId': currentEvent.id }" :auto-upload="false" drag>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('现场人员导入模板.xlsx')">下载模板</el-link> -->
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="seismicIntensityMapData">
import { dataMethod } from '@/utils/spanTable.js'
import { getToken, } from "@/utils/auth";
import useEventStore from "@/store/modules/event";
import { getAllList, getDetail, updateData, del, getSubList ,saveData} from "@/api/seismicIntensityMap/seismicIntensityMapData.js"
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const spanObj = ref();
const option1 = ref([]);
const option = ref([{ label: 'I类', value: 'I类' }, { label: 'II类', value: 'II类' }, { label: 'III-1类', value: 'III-1类' }, { label: 'III-2类', value: 'III-2类' }, { label: 'IV类', value: 'IV类' }
    , { label: 'V-1类', value: 'V-1类' }, { label: 'V-2类', value: 'V-2类' }, { label: 'V-3类', value: 'V-3类' }]);
/*** 导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/floorArea/reportImport"
});
const validatePositiveNumver = (rule, value, callback) => {
    if (/(^[1-9]\d*$)/.test(value)) {
        callback()
    } else if (!value) {
        callback(new Error('总建筑面积不能为空'))
    } else {
        callback(new Error('请输入正整数'))
    }
};
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        area: undefined,
        structureType: undefined,
    },
    form: {
    },
    rules: {
        expertOpinion: [{ required: true, message: "专家意见不能为空", trigger: "blur"}],
        expertOpinionPdf: [
		      { required: true, message: "专家意见（pdf）不能为空" }
		    ],
		    seismicIntensityMap: [
		      { required: true, message: "地震烈度图（终版）jpg不能为空" }
		    ],

    }
})
const { queryParams, form, rules } = toRefs(data)

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    ids.value = selection.map((item) => item.id);
};

// 导出模版
function importTemplate(name) {
    proxy.downloadTemplate("/template/download", {
        fileName: name
    }, name);
};


/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +  response.data?response.data:response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};


// 编辑
function handleEdit(row) {
    title.value = '地震烈度图资料'
    detail(row.xsemId);
}


// 查看
function detail(id) {
    getDetail({ xsemId: id }).then(res => {
        open.value = true;
        proxy.resetForm("addRef");
        form.value = res.data[0];
    })
}

// 保存
function save() {
	const fileList = JSON.parse(JSON.stringify(proxy.$refs["fileUpload"].fileList));
	const fileList1 = JSON.parse(JSON.stringify(proxy.$refs["fileUpload1"].fileList));
	const imageList = JSON.parse(JSON.stringify(proxy.$refs["imageUpload"].fileList));
	const attachIds1 = [];
	const attachIds2 = [];
	const attachIds3 = [];
	for(var i = 0; i<fileList.length;i++) {
   	attachIds1.push(fileList[i].attachId)
 	}
	for(var i = 0; i<fileList1.length;i++) {
   	attachIds2.push(fileList1[i].attachId)
 	}
	for(var i = 0; i<imageList.length;i++) {
   	attachIds3.push(imageList[i].attachId)
 	}
	form.value.expertOpinionPdf = attachIds1.join(",");
	form.value.seismicIntensityMap = attachIds3.join(",");
	form.value.processMaterials = attachIds2.join(",");
	proxy.$refs["addRef"].validate(valid => {
    if (valid) {
			saveData({ ...form.value}).then(res => {
        proxy.$modal.msgSuccess("保存成功");
        open.value = false;
        getList();
     })    
    }
	})

}

/** 删除按钮操作 */
function handleDelete(row) {
    let ids = row.id || ids.value;
    proxy.$modal
        .confirm("是否确认删除该信息，请确认是否要删除？",)
        .then(function () {
            return del(ids);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}


/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

// 合并列
function objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
  //判断合并列
  const _row = spanObj.value[column.property] ? spanObj.value[column.property][rowIndex] : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  }
}

/** 查询数据列表 */
function getList() {
    if (currentEvent.value) {
        loading.value = true;
        getAllList({xsemId: currentEvent.value.id }).then(response => {
            dataList.value = response.data ? response.data : [];
//          total.value = response.data.total;
            loading.value = false;
        });
    } else {
        dataList.value = [];
        total.value = 0;
    }
}

/** 查询评估子区列表 */
function getSubLists() {
    if (currentEvent.value) {
        getSubList({ xsemId: currentEvent.value.id }).then(response => {
            option1.value = response.data;
        });
    }
}
const imgUploadSuccess = (id) => {
	form.value.picture = id
	proxy.$refs['addRef'].clearValidate('picture')
}
// 下载文件
function handleDownload(attachId) {
	location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId="+ encodeURIComponent(attachId);
}
onMounted(() => {
    setTimeout(() => {
        getList();
        // getSubLists();
    }, 200)
})
</script>
  
<style scoped lang="scss">
.title {
    margin: 0 0 20px !important;
}
</style>
  
  